package com.jy.appmarket.network.resultdata;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.text.TextUtils;

import com.jy.app.market.idata.Doc;
import com.jy.app.market.idata.card.CardApk;
import com.jy.app.market.idata.data.MapApk;
import com.jy.appmarket.network.engine.cachestrategy.NamedCacheStrategy;

public class EssentialResultData extends BaseResultData {
	// private static final String TAG =
	// EssentialResultData.class.getSimpleName();
	private Map<String, List<CardApk>> mEssentials;
	private long mDataVersion = 0;
	private boolean mCacheVaild;

	public EssentialResultData(Context context) {
		// this.mContext = context;
	}

	public boolean isCacheVaild() {
		return mCacheVaild;
	}

	public long getDataVersion() {
		return mDataVersion;
	}

	public Map<String, List<CardApk>> getEssentials() {
		return mEssentials;
	}

	@Override
	public boolean parseResult(String result) {
		if (TextUtils.isEmpty(result)) {
			return false;
		}

		Doc doc = Doc.fromJson(result);

		if (doc == null) {
			return false;
		}
		NamedCacheStrategy ncs = new NamedCacheStrategy("essential");
		String real = getFileContent(ncs.getRealCacheFile());
		if (real != null && real.length() == result.length()) {
			mCacheVaild = true;
		} else {
			mCacheVaild = false;
			ncs.getRealCacheFile().delete();
			try {
				FileOutputStream fos = new FileOutputStream(ncs.getRealCacheFile());
				fos.write(result.getBytes("UTF-8"));
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		setDataType(doc.getDataType());
		setStatus(doc.getStatus());
		setMessage(doc.getMessage());

		if (doc.isOk()) {
			if (doc.isType(MapApk.class)) {
				MapApk mapApk = doc.getData();
				mDataVersion = mapApk.getDataVersion();
				mEssentials = mapApk.getApks();
				return true;
			}
		}
		return false;
	}

	private String getFileContent(File file) {
		if (!file.exists()) {
			return null;
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			if (fis.available() <= 0) {
				return null;
			}
			byte[] bytes = new byte[fis.available()];
			fis.read(bytes);

			return new String(bytes, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (Exception e) {
					// ignore
				}
			}
		}
		return null;
	}
}
